package org.hzz.work.tree;

import org.hzz.common.utils.FastJsonUtil;
import org.hzz.common.utils.TreeDataUtils;
import org.hzz.work.tree.convert.CategoryConverter;
import org.hzz.work.tree.vo.Category;
import org.hzz.work.tree.vo.CategoryVo;

import java.util.List;

/**
 * 将List转换为Tree 使用通用工具{@link org.hzz.common.utils.TreeDataUtils}
 *
 * @author 胖卡
 * @version 1.0.0
 * @date 2024/7/13
 */
public class ListToTreeMain2 {

    final static CategoryConverter categoryConverter = CategoryConverter.INSTANCE;

    public static void main(String[] args) {
        List<Category> data = getDataFromDb();
        String jsonStr = FastJsonUtil.toJSONStr(data);

        System.out.println(jsonStr);

        System.out.println("===============================");


        List<CategoryVo> results = TreeDataUtils.parseToTree(
                data,
                categoryConverter,
                new CategoryDataProcessor());

        String treeJson = FastJsonUtil.toJSONStr(results);
        System.out.println(treeJson);

    }


    public static List<Category> getDataFromDb() {
        return List.of(
                new Category(2, 1, "Java开发"),
                new Category(1, 0, "IT.互联网"),
                new Category(3, 2, "SpringBoot"),
                new Category(4, 2, "MyBatis"),
                new Category(5, 0, "阅读"),
                new Category(6, 1, "前端开发")
        );
    }


    static class CategoryDataProcessor implements TreeDataUtils.DataProcessor<CategoryVo, Category> {

        @Override
        public Object getParentKey(Category category) {
            return category.getParentId();
        }

        @Override
        public Object getKey(Category category) {
            return category.getId();
        }

        @Override
        public Object getRootKey() {
            return 0;
        }

        @Override
        public List<CategoryVo> getChild(CategoryVo categoryVo) {
            return categoryVo.getChildren();
        }

        @Override
        public void setChild(CategoryVo parent, List<CategoryVo> child) {
            parent.setChildren(child);
        }

        @Override
        public void addChildElement(CategoryVo parent, CategoryVo childElement) {
            parent.getChildren().add(childElement);
        }

        @Override
        public CategoryVo createNewObject() {
            return new CategoryVo();
        }
    }
}
